package com.cjm.algorithm.tree;

import com.cjm.algorithm.TreeNode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

public class PostorderTraversal145 {
    public List<Integer> postorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> res = new ArrayList<>();
        if (root!=null) stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode pop = stack.pop();
            res.add(pop.val);
            if (pop.left != null) stack.add(pop.left);
            if (pop.right != null) stack.add(pop.right);
        }
        Collections.reverse(res);
        return res;
    }

    private static List<Integer> m1(TreeNode root) {
        if (root == null) return new ArrayList<>();
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode pop = stack.pop();
            if (pop != null) {
                res.add(pop.val);
                stack.add(pop.right);
                stack.add(pop.left);
            }
        }
        return res;
    }
}
